package anagramUtils;

import exceptions.FileAccessException;
import exceptions.FileCreationException;
import exceptions.WrongPathFileException;

import java.util.HashMap;
import java.util.List;
import java.util.Scanner;


public class ConsoleMonitor {

    private final AnagramFinder anagramFinder;
    private final Scanner scanner;
    private final ReadFromFile fromFile;
    private final WriteToFile toFile;


    public ConsoleMonitor(Scanner scanner, AnagramFinder anagramFinder, ReadFromFile fromFile, WriteToFile toFile) {
        this.scanner = scanner;
        this.anagramFinder = anagramFinder;
        this.fromFile = fromFile;
        this.toFile = toFile;
    }

    public void startMonitor() {
        System.out.println("Input path to txt file you want to read: ");
        String inputFile = scanner.nextLine();
        while (!checkIsEmptyLine(inputFile)) {
            inputFile = scanner.nextLine();
        }
        System.out.println("Input path to file you want to write anagrams. If given file does not exist, it will be created automatically: ");
        String outputFile = scanner.nextLine();
        while (!checkIsEmptyLine(outputFile)) {
            outputFile = scanner.nextLine();
        }

        try {
            findAnagram(inputFile, outputFile);
        } catch (WrongPathFileException e) {
            System.out.println(e.getMessage());
        } catch (FileAccessException e) {
            System.out.println(e.getMessage());
        } catch (FileCreationException e) {
            System.out.println(e.getMessage());
        }


        scanner.close();
    }

    private void findAnagram(String inputFile, String outputFile) throws WrongPathFileException, FileAccessException, FileCreationException {

        String[] words = fromFile.readFile(inputFile);
        HashMap<String, List<String>> result = anagramFinder.parse(words);
        toFile.writeToFile(outputFile, result);

    }

    private boolean checkIsEmptyLine(String s) {
        if (s.trim().isEmpty()) {
            System.out.println(" File path must not be empty, please try again: ");
            return false;
        }
        return true;
    }
}
